package com.fingard.dsp.bank.directbank.abc02;

import com.fingard.client.DspClient;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IBalanceCheckConfirm;
import com.fingard.dsp.bank.helpers.FileType;
import com.fingard.dsp.bank.reqrespobj.balancecheckconfirm.ReqBalCheckConfirmQry;
import com.fingard.dsp.bank.reqrespobj.balancecheckconfirm.RetAtsBalCheckConfirmQry;
import com.fingard.dsp.bank.reqrespobj.balancecheckconfirm.detail.RetAtsBalCheckConfirmDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Date;

public class ABC02BalanceCheckConfirm extends ABC02Base implements IBalanceCheckConfirm {
    @Override
    public RetAtsBalCheckConfirmQry d_7509_BalCheckConfirm(ReqBalCheckConfirmQry p_req7509) throws Exception {
        RetAtsBalCheckConfirmQry retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
        retAts.writeStart();
        try {
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "CMLR35";
            while (p_req7509.readRecord()) {
                String tmpDataFileName = p_req7509.readedDetail.statementNumber + "." + bankFront.org + "_" + bankFront.operator + "." + Format.Date8Format.format(new Date());
                XmlTextWriter xmlWriter = new XmlTextWriter();
                bankHeader.ReqSeqNo = p_req7509.reqHeader.transSeqID;
                writeCommonHeader(xmlWriter, bankHeader);

                xmlWriter.writeStartElement("TCAS");
                xmlWriter.writeElementString("BillSerial", p_req7509.readedDetail.statementNumber);
                xmlWriter.writeElementString("AllTrue", "N");
                xmlWriter.writeElementString("AllFalse", "N");
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("Cmp");
                xmlWriter.writeElementString("BatchFileName", tmpDataFileName);

                /**
                 * 文件内容格式：
                 * 账单编号|省号|账号|币种|账户类型|余额|结果|
                 */
                StringBuilder tmpSbData = new StringBuilder();
                StringBuilder tmpSbSeqIDData = new StringBuilder();
                if (tmpSbSeqIDData.length() > 0) {
                    tmpSbSeqIDData.append("\r\n");
                }
                tmpSbSeqIDData.append(p_req7509.readedDetail.iSeqno);
                tmpSbData.append(p_req7509.readedDetail.statementNumber + "|");
                tmpSbData.append(p_req7509.readedDetail.actArea + "|");
                tmpSbData.append(p_req7509.readedDetail.actNum + "|");
                tmpSbData.append(p_req7509.readedDetail.actCur + "|");
                tmpSbData.append(convertAccountTypeToBank(p_req7509.readedDetail.actNum) + "|");
                tmpSbData.append(p_req7509.readedDetail.custActBal + "|");
                tmpSbData.append(p_req7509.readedDetail.dzFlag + "|");
                tmpSbData.append("\r\n");
                String tmpLocalMarkPath = getTempFileDirectory() + File.separator + p_req7509.readedDetail.statementNumber + ".txt";
                WriteBankLogLn2("明细序号映射文件路径: " + tmpLocalMarkPath);
                FileHelper.writeFile(tmpLocalMarkPath, tmpSbSeqIDData);
                String tmpFilePath = StringHelper.trimEnd(bankFront.bkPayFolder, File.separator) + File.separator + tmpDataFileName;
                if ("dspfileserver".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                    WriteBankLogLn("accessBkFileMode：" + bankFront.accessBkFileMode);
                    DspClient dspClient = new DspClient(bankFront.dspFileServer);
                    dspClient.charsetName = getCharset();
                    TcpReceiver retReceiver = dspClient.putFile(tmpSbData.toString(), FileType.bankFile, tmpFilePath, false);
                    if (retReceiver.isCompleted) {
                        String retXml = new String(retReceiver.recBytes, retReceiver.contentStartIndex, retReceiver.contentLength, retReceiver.charsetName);
                        XmlTextReader retXmlRd = new XmlTextReader(retXml);
                        if ("0".equals(retXmlRd.getSimpleText("RespCode"))) {
                            WriteBankLogLn("文件保存至前置机" + tmpFilePath + "成功");
                        } else {
                            WriteBankLogLn("文件保存至前置机" + tmpFilePath + "失败，响应报文：" + retXml);
                        }
                    } else {
                        WriteBankLogLn("文件" + tmpFilePath + "保存失败：" + retReceiver.getConnMsg());
                        if (retReceiver.connState.equals(ConnState.FAIL)) {
                            WriteBankLogLn("连接主DSP服务" + bankFront.dspFileServer + "失败");
                        }
                    }
                } else if ("ftp".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                    FileHelper.writeFile(tmpFilePath, tmpSbData.toString(), getCharset());
                    WriteBankLogLn("开始上传文件至FTP...");
                    FtpSet ftpSet = bankFront.getFtpSet("balCheConfirm");
                    String ftpFilePath = StringHelper.trimEndFileSp(ftpSet.upDir) + "/" + tmpDataFileName;
                    int result = FtpUtil.ftpUploading(ftpSet, tmpFilePath, ftpFilePath);
                    if (result == 0 || result == 1) {
                        WriteBankLogLn("上传文件成功...");
                    } else {
                        WriteBankLogLn("上传文件失败...");
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo("上传文件失败...");
                        return retAts;
                    }
                } else {
                    WriteBankLogLn("请求代收付文件内容为:" + tmpSbData.toString());
                    WriteBankLogLn("文件传送地址为:" + tmpFilePath);
                    FileHelper.writeFile(tmpFilePath, tmpSbData.toString(), getCharset());
                }
                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpAbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpAbMsg);

                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                        String tmpRetMsg = tmpBkReader.getFirstText("/ap/RespInfo");
                        if (isActiveRetCode(tmpRetCode)) {
                            RetAtsBalCheckConfirmDetail tmpRetDetail = new RetAtsBalCheckConfirmDetail();
                            while (tmpBkReader.read("/ap/Cmp")) {
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.respInfo = tmpRetMsg;
                                tmpRetDetail.bnkReqNo = tmpBkReader.readedXElement.getSingleText("CmeSeqNo");
                                retAts.writeRetDetail(tmpRetDetail, p_req7509.isBatch);
                            }
                        } else {
                            retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
                            retAts.writeStart();//写返回ATS的统一头部信息
                        }
                    } else {
                        retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
                        retAts.writeStart();//写返回ATS的统一头部信息
                    }
                } else {
                    retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
                    retAts.writeStart();//写返回ATS的统一头部信息
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpStrRet[1]);
                }
            }
        } catch (Exception e) {
            retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }
}
